package com.study.designpattern.fliyweight;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class FlyWeightTest {
    public static void main(String[] args) {
        TreeFactory factory = new TreeFactory();
        TreeNode treeNode=new TreeNode(3,4,factory.getTree("桦树","white"));
        TreeNode treeNode1=new TreeNode(4,4,factory.getTree("桦树","white"));

        TreeNode treeNode2=new TreeNode(5,4,factory.getTree("柳树","green"));
        //这里无论data是什么，只要柳树已经存在，就只会是柳树的data:green.只会创建一次柳树
        TreeNode treeNode3=new TreeNode(5,4,factory.getTree("柳树","green"));
    }
}

class Tree{
    private final String name;
    private final  String data;
    public Tree(String name, String data) {
        this.name = name;
        this.data = data;
        System.out.println("[name:"+name+","+"data:"+data+"] created!");
    }
    public String getName() {
        return name;
    }
    public String getData() {
        return data;
    }
}
class TreeFactory{
    private static Map<String,Tree> map=new ConcurrentHashMap<>();
    public static Tree getTree(String name,String data){
        if(map.containsKey(name)){
            return map.get(name);
        }
        else {
            Tree tree=new Tree(name,data);
            map.put(name,tree);
            System.out.println("[name:"+name+","+"data:"+data+"] got!");
            return tree;
        }
    }
}
@NoArgsConstructor
@Data
@AllArgsConstructor
class TreeNode{
    private int x;
    private int y;
    private Tree tree;

}